package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.qf.pojo.DtsCategory;
import com.qf.service.CategoryService;
import com.qf.util.ResponseUtil;
import com.qf.vo.CatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public Object list(Integer id, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10")Integer limit,
                       @RequestParam(defaultValue = "add_time") String sort,
                       @RequestParam(defaultValue = "desc")String order){
        //1. 查询并返回分页对象
        IPage<DtsCategory> resultPage = categoryService.queryCategoryPage(id,name,page,limit,sort,order);

        //获取结果集
        List<DtsCategory> list = resultPage.getRecords();
        //获取查询总条数
        long total = resultPage.getTotal();

        //封装对象返回
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", list);

        return ResponseUtil.ok(data);

    }

    @GetMapping("/l1")
    public Object l1(){

        List<DtsCategory> label1 = categoryService.findByLabel();
        List<Map<String,Object>> data=new ArrayList<>(label1.size());

        for (DtsCategory category : label1) {

            HashMap<String, Object> list = new HashMap<>();
            list.put("value", category.getId());
            list.put("label", category.getName());
            data.add(list);
        }
        return ResponseUtil.ok(data);
    }


    @PostMapping("/create")
    public Object add(@RequestBody DtsCategory category){
        int add = categoryService.add(category);

        if(add == 0){
            return  ResponseUtil.badArgument();
        }
        return ResponseUtil.ok();
    }


    @PostMapping("/update")
    public Object update(@RequestBody DtsCategory category){
        int count = categoryService.update(category);
        if (count == 0) {
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok();
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody DtsCategory category){
        Integer id = category.getId();

        if(id==null){
            return ResponseUtil.badArgument();
        }

        categoryService.deleteByid(id);

        return ResponseUtil.ok();

    }
}
